package com.wsx.sky.dubbo.service.impl;

import com.wsx.sky.dubbo.bean.DubboRequest;
import com.wsx.sky.dubbo.bean.DubboResponse;
import com.wsx.sky.dubbo.model.DubboServer;
import com.wsx.sky.dubbo.service.DubboService;
import com.wsx.sky.redis.RedisService;
import lombok.Setter;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.dubbo.service.impl.DubboServiceImpl
 * @Description: TODO
 * @date 2018/12/11
 */
public class DubboServiceImpl implements DubboService {

    @Setter private RedisService redisService;

    @Setter private MongoTemplate mongoTemplate;


    @Override
    public DubboResponse request(DubboRequest dubboRequest) {
        System.out.println(dubboRequest.getTraceid());
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(dubboRequest.getName()));
        DubboServer dubboServer = mongoTemplate.findOne(query, DubboServer.class, "dubbo_server");
        if (null != dubboServer) {
            return new DubboResponse().buildMsg(dubboServer.getName());
        }
        return new DubboResponse(40001).buildMsg("mongo data is null");
    }

    @Override
    public DubboResponse get(String name) {
        String value = redisService.getString(name);
        if (StringUtils.isEmpty(value)) {
            Query query = new Query();
            query.addCriteria(Criteria.where("name").is(name));
            DubboServer dubboServer = mongoTemplate.findOne(query, DubboServer.class, "dubbo_server");
            if (null != dubboServer) {
                value = dubboServer.getName();
                if (!StringUtils.isEmpty(value)) {
                    redisService.setString(name, dubboServer.getName());
                }
            }
        }
        if (!StringUtils.isEmpty(value)) {
            return new DubboResponse().buildMsg(value);
        }
        return new DubboResponse(40001).buildMsg("mongo data is null");
    }
}
